// 全局变量
let currentData = [];
let currentPage = 1;
let pageSize = 20;
let totalPages = 1;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeUpload();
    loadProjectGroups();
    loadExistingData();
    updateHeaderStats();
});

// 初始化文件上传功能
function initializeUpload() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');
    
    if (!uploadArea || !fileInput) {
        console.warn('上传元素未找到');
        return;
    }
    
    // 点击上传区域触发文件选择
    uploadArea.addEventListener('click', () => {
        fileInput.click();
    });
    
    // 文件选择事件
    fileInput.addEventListener('change', handleFileSelect);
    
    // 拖拽上传功能
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });
    
    uploadArea.addEventListener('dragleave', () => {
        uploadArea.classList.remove('dragover');
    });
    
    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileUpload(files[0]);
        }
    });
}

// 加载项目组列表
function loadProjectGroups() {
    fetch('/project_groups')
    .then(response => response.json())
    .then(data => {
        if (data.project_groups) {
            const select = document.getElementById('projectGroupFilter');
            if (select) {
                // 清空现有选项（保留"全部项目组"）
                select.innerHTML = '<option value="">全部项目组</option>';
                
                // 添加项目组选项
                data.project_groups.forEach(group => {
                    const option = document.createElement('option');
                    option.value = group;
                    option.textContent = group;
                    select.appendChild(option);
                });
            }
        }
    })
    .catch(error => {
        console.log('获取项目组列表失败：', error);
    });
}

// 加载现有数据
function loadExistingData() {
    fetch('/data')
    .then(response => response.json())
    .then(data => {
        if (data.total > 0) {
            currentData = data.data;
            updateHeaderStats();
            // 自动显示第一页数据
            filterData(1);
        }
    })
    .catch(error => {
        console.log('获取历史数据失败：', error);
    });
}

// 更新头部统计信息
function updateHeaderStats() {
    const statsElement = document.getElementById('headerStats');
    if (statsElement) {
        if (currentData.length > 0) {
            const projectGroups = new Set(currentData.map(item => item.项目组)).size;
            const employees = new Set(currentData.map(item => item.编辑人)).size;
            statsElement.textContent = `共 ${currentData.length} 条记录 | ${projectGroups} 个项目组 | ${employees} 名员工`;
        } else {
            statsElement.textContent = '暂无数据';
        }
    }
}

// 模态框控制
function openUploadModal() {
    const modal = document.getElementById('uploadModal');
    const overlay = document.getElementById('modalOverlay');
    if (modal && overlay) {
        modal.classList.add('active');
        overlay.classList.add('active');
    }
}

function closeUploadModal() {
    const modal = document.getElementById('uploadModal');
    const overlay = document.getElementById('modalOverlay');
    if (modal && overlay) {
        modal.classList.remove('active');
        overlay.classList.remove('active');
    }
}

function openAIModal() {
    if (currentData.length === 0) {
        alert('请先上传Excel文件');
        return;
    }
    const modal = document.getElementById('aiModal');
    const overlay = document.getElementById('modalOverlay');
    if (modal && overlay) {
        modal.classList.add('active');
        overlay.classList.add('active');
    }
}

function closeAIModal() {
    const modal = document.getElementById('aiModal');
    const overlay = document.getElementById('modalOverlay');
    if (modal && overlay) {
        modal.classList.remove('active');
        overlay.classList.remove('active');
    }
}

// 点击遮罩层关闭模态框
document.addEventListener('DOMContentLoaded', function() {
    const overlay = document.getElementById('modalOverlay');
    if (overlay) {
        overlay.addEventListener('click', function() {
            closeUploadModal();
            closeAIModal();
        });
    }
});

// 处理文件选择
function handleFileSelect(event) {
    const file = event.target.files[0];
    if (file) {
        handleFileUpload(file);
    }
}

// 处理文件上传
function handleFileUpload(file) {
    const resultDiv = document.getElementById('uploadResult');
    if (!resultDiv) return;
    
    // 检查文件类型
    if (!file.name.match(/\.(xlsx|xls)$/i)) {
        showError(resultDiv, '请选择Excel文件（.xlsx或.xls格式）');
        return;
    }
    
    // 检查文件大小（500MB）
    if (file.size > 500 * 1024 * 1024) {
        showError(resultDiv, '文件大小不能超过500MB');
        return;
    }
    
    // 显示上传进度
    resultDiv.style.display = 'block';
    resultDiv.innerHTML = '<div class="loading">正在上传和解析文件...</div>';
    
    // 创建FormData对象
    const formData = new FormData();
    formData.append('file', file);
    
    // 发送文件到后端
    fetch('/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showError(resultDiv, data.error);
        } else {
            showSuccess(resultDiv, `文件上传成功！解析到 ${data.records_count} 条记录`);
            
            // 显示解析时间
            if (data.parse_time) {
                resultDiv.innerHTML += `<div style="margin-top: 10px; color: #6c757d; font-size: 14px;">解析耗时: ${data.parse_time}</div>`;
            }
            
            // 刷新数据
            setTimeout(() => {
                loadExistingData();
                loadProjectGroups();
                closeUploadModal();
            }, 2000);
        }
    })
    .catch(error => {
        showError(resultDiv, '上传失败：' + error.message);
    });
}

// 筛选数据（支持分页）
function filterData(page = 1) {
    const startDate = document.getElementById('startDate');
    const endDate = document.getElementById('endDate');
    const projectGroup = document.getElementById('projectGroupFilter');
    const resultDiv = document.getElementById('summaryResult');
    
    if (!resultDiv) return;
    
    currentPage = page;
    
    resultDiv.innerHTML = '<div class="loading">正在筛选数据...</div>';
    
    const params = new URLSearchParams();
    if (startDate && startDate.value) params.append('start_date', startDate.value);
    if (endDate && endDate.value) params.append('end_date', endDate.value);
    if (projectGroup && projectGroup.value) params.append('project_group', projectGroup.value);
    params.append('page', page);
    params.append('page_size', pageSize);
    
    fetch(`/summary?${params.toString()}`)
    .then(response => response.json())
    .then(data => {
        console.log('API响应数据:', data); // 调试日志
        
        if (data.error) {
            showError(resultDiv, data.error);
        } else if (data.data && data.pagination) {
            displaySummaryData(data.data, resultDiv, data.pagination);
        } else {
            showError(resultDiv, '数据格式错误');
        }
    })
    .catch(error => {
        console.error('筛选数据失败:', error);
        showError(resultDiv, '数据筛选失败：' + error.message);
    });
}

// 显示汇总数据（支持分页）
function displaySummaryData(groupedData, container, pagination) {
    if (Object.keys(groupedData).length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <div class="empty-icon">🔍</div>
                <h3>没有找到符合条件的数据</h3>
                <p>请调整筛选条件或上传新的数据文件</p>
            </div>
        `;
        return;
    }
    
    let html = '';
    let currentPageRecords = 0;
    
    // 获取筛选条件
    const startDate = document.getElementById('startDate');
    const endDate = document.getElementById('endDate');
    const hasDateFilter = (startDate && startDate.value) || (endDate && endDate.value);
    
    // 按项目组名称排序
    const sortedProjectGroups = Object.keys(groupedData).sort();
    
    sortedProjectGroups.forEach(projectGroup => {
        const records = groupedData[projectGroup];
        
        // 确保records是数组
        if (!Array.isArray(records)) {
            console.warn('项目组数据不是数组:', projectGroup, records);
            return;
        }
        
        currentPageRecords += records.length;
        
        // 获取日期范围信息
        const dateInfo = getDateRangeInfo(records);
        
        html += `
            <div class="project-group">
                <div class="project-group-header">
                    <div>
                        <span class="project-name">${projectGroup}</span>
                        <span class="date-range">${dateInfo}</span>
                    </div>
                    <span class="record-count">${records.length} 条记录</span>
                </div>
                <div class="project-group-content">
        `;
        
        // 确保记录按日期倒序显示
        const sortedRecords = records.sort((a, b) => {
            const dateA = parseDate(a.填写日期);
            const dateB = parseDate(b.填写日期);
            return dateB - dateA; // 倒序
        });
        
        sortedRecords.forEach((record, index) => {
            html += `
                <div class="work-item">
                    <div class="work-item-header">
                        <span class="employee-name">${record.编辑人 || '未知'}</span>
                        <span class="work-date">${record.填写日期 || '未知日期'}</span>
                    </div>
                    <div class="work-content">${record.今日工作总结 || '无工作总结'}</div>
                </div>
            `;
        });
        
        html += `
                </div>
            </div>
        `;
    });
    
    // 添加统计信息和分页信息
    const sortInfo = hasDateFilter ? ' (按筛选条件排序)' : ' (按日期倒序排列)';
    const statsHtml = `
        <div class="summary-stats">
            <div class="stats-content">
                <div class="stats-main">
                    <strong>📊 筛选结果：</strong>共找到 ${pagination.total_records} 条记录，涉及 ${Object.keys(groupedData).length} 个项目组${sortInfo}
                </div>
                <div class="stats-page">
                    显示第 ${pagination.start_index}-${pagination.end_index} 条记录 (第 ${pagination.current_page}/${pagination.total_pages} 页)
                </div>
            </div>
        </div>
    `;
    
    // 生成分页控件
    const paginationHtml = generatePaginationHtml(pagination);
    
    container.innerHTML = statsHtml + html + paginationHtml;
    
    // 更新全局分页变量
    currentPage = pagination.current_page;
    totalPages = pagination.total_pages;
}

// 生成分页控件HTML
function generatePaginationHtml(pagination) {
    if (pagination.total_pages <= 1) {
        return '';
    }
    
    let html = '<div class="pagination-container"><div class="pagination">';
    
    // 上一页按钮
    if (pagination.has_prev) {
        html += `<button class="page-btn" onclick="filterData(${pagination.current_page - 1})" title="上一页">‹</button>`;
    } else {
        html += `<button class="page-btn disabled">‹</button>`;
    }
    
    // 页码按钮
    const startPage = Math.max(1, pagination.current_page - 2);
    const endPage = Math.min(pagination.total_pages, pagination.current_page + 2);
    
    // 第一页
    if (startPage > 1) {
        html += `<button class="page-btn" onclick="filterData(1)">1</button>`;
        if (startPage > 2) {
            html += `<span class="page-ellipsis">...</span>`;
        }
    }
    
    // 中间页码
    for (let i = startPage; i <= endPage; i++) {
        if (i === pagination.current_page) {
            html += `<button class="page-btn active">${i}</button>`;
        } else {
            html += `<button class="page-btn" onclick="filterData(${i})">${i}</button>`;
        }
    }
    
    // 最后一页
    if (endPage < pagination.total_pages) {
        if (endPage < pagination.total_pages - 1) {
            html += `<span class="page-ellipsis">...</span>`;
        }
        html += `<button class="page-btn" onclick="filterData(${pagination.total_pages})">${pagination.total_pages}</button>`;
    }
    
    // 下一页按钮
    if (pagination.has_next) {
        html += `<button class="page-btn" onclick="filterData(${pagination.current_page + 1})" title="下一页">›</button>`;
    } else {
        html += `<button class="page-btn disabled">›</button>`;
    }
    
    html += '</div>';
    
    // 添加页面大小选择器
    html += `
        <div class="page-size-selector">
            <label>每页显示：</label>
            <select onchange="changePageSize(this.value)">
                <option value="10" ${pageSize === 10 ? 'selected' : ''}>10条</option>
                <option value="20" ${pageSize === 20 ? 'selected' : ''}>20条</option>
                <option value="50" ${pageSize === 50 ? 'selected' : ''}>50条</option>
                <option value="100" ${pageSize === 100 ? 'selected' : ''}>100条</option>
            </select>
        </div>
    `;
    
    html += '</div>';
    
    return html;
}

// 改变每页显示数量
function changePageSize(newPageSize) {
    pageSize = parseInt(newPageSize);
    filterData(1); // 重新从第一页开始
}

// 获取日期范围信息
function getDateRangeInfo(records) {
    // 确保records是数组
    if (!Array.isArray(records) || records.length === 0) {
        return '';
    }
    
    try {
        const dates = records
            .map(record => {
                if (!record || !record.填写日期) return null;
                return parseDate(record.填写日期);
            })
            .filter(date => date && !isNaN(date.getTime()));
            
        if (dates.length === 0) return '';
        
        dates.sort((a, b) => a - b);
        const minDate = dates[0];
        const maxDate = dates[dates.length - 1];
        
        const formatDate = (date) => {
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit'
            });
        };
        
        if (minDate.getTime() === maxDate.getTime()) {
            return formatDate(minDate);
        } else {
            return `${formatDate(minDate)} ~ ${formatDate(maxDate)}`;
        }
    } catch (error) {
        console.error('获取日期范围信息失败:', error);
        return '';
    }
}

// 解析日期字符串为Date对象
function parseDate(dateStr) {
    if (!dateStr || typeof dateStr !== 'string') {
        return new Date(1900, 0, 1);
    }
    
    try {
        // 清理日期字符串
        const cleanDateStr = dateStr.trim();
        
        // 尝试直接解析
        const date = new Date(cleanDateStr);
        if (!isNaN(date.getTime()) && date.getFullYear() > 1900) {
            return date;
        }
        
        // 如果直接解析失败，尝试手动解析
        if (cleanDateStr.includes('/')) {
            const parts = cleanDateStr.split('/');
            if (parts.length === 3) {
                const [part1, part2, part3] = parts.map(p => parseInt(p));
                if (part1 > 1900) {
                    // YYYY/MM/DD
                    return new Date(part1, part2 - 1, part3);
                } else if (part3 > 1900) {
                    // MM/DD/YYYY
                    return new Date(part3, part1 - 1, part2);
                }
            }
        } else if (cleanDateStr.includes('-')) {
            const parts = cleanDateStr.split('-');
            if (parts.length === 3) {
                const [part1, part2, part3] = parts.map(p => parseInt(p));
                if (part1 > 1900) {
                    // YYYY-MM-DD
                    return new Date(part1, part2 - 1, part3);
                } else if (part3 > 1900) {
                    // MM-DD-YYYY
                    return new Date(part3, part1 - 1, part2);
                }
            }
        }
        
        return new Date(1900, 0, 1); // 默认日期
    } catch (e) {
        console.warn('日期解析失败:', dateStr, e);
        return new Date(1900, 0, 1);
    }
}

// 清空筛选条件
function clearFilters() {
    const startDate = document.getElementById('startDate');
    const endDate = document.getElementById('endDate');
    const projectGroup = document.getElementById('projectGroupFilter');
    
    if (startDate) startDate.value = '';
    if (endDate) endDate.value = '';
    if (projectGroup) projectGroup.value = '';
    
    // 重置到第一页
    currentPage = 1;
    filterData(1);
}

// 刷新数据
function refreshData() {
    loadExistingData();
    loadProjectGroups();
}

// AI提问功能
function askAI() {
    const questionElement = document.getElementById('aiQuestion');
    const resultDiv = document.getElementById('aiResult');
    
    if (!questionElement || !resultDiv) return;
    
    const question = questionElement.value.trim();
    
    if (!question) {
        showError(resultDiv, '请输入您的问题');
        return;
    }
    
    // 显示处理中状态
    resultDiv.innerHTML = `
        <div class="loading">
            <div>🤖 AI正在分析中，请稍候...</div>
            <div style="margin-top: 10px; font-size: 14px; color: #666;">
                正在处理数据，大量数据可能需要分批处理
            </div>
        </div>
    `;
    
    fetch('/ai_analysis', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            question: question
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showError(resultDiv, data.error);
        } else {
            displayAIResponse(data, resultDiv);
        }
    })
    .catch(error => {
        showError(resultDiv, 'AI分析失败：' + error.message);
    });
}

// 显示AI回答
function displayAIResponse(data, container) {
    let html = `
        <div class="ai-question">
            <strong>问题：</strong>${data.question}
        </div>
    `;
    
    // 显示批处理信息
    if (data.batch_count && data.batch_count > 1) {
        html += `
            <div class="ai-batch-info">
                <strong>处理信息：</strong>已完成分批处理（共${data.batch_count}批，${data.data_count}条记录）
            </div>
        `;
    }
    
    // 处理AI响应文本，优化显示格式
    let cleanAnswer = cleanAIResponse(data.answer);
    
    // 添加展开/收起功能，确保完整内容显示
    html += `
        <div class="ai-response-container">
            <div class="ai-response" id="ai-response-content">
                ${cleanAnswer}
            </div>
            <div class="ai-response-actions">
                <button class="btn btn-sm btn-outline-secondary" onclick="toggleAIResponseCollapse()" id="expand-btn" style="display: none;">
                    收起内容
                </button>
                <button class="btn btn-sm btn-outline-primary" onclick="copyAIResponse()">
                    复制内容
                </button>
            </div>
        </div>
        <div style="margin-top: 15px; color: #6c757d; font-size: 14px; text-align: center;">
            基于 ${data.data_count} 条日报数据进行分析
        </div>
    `;
    
    container.innerHTML = html;
    
    // 内容现在默认完整显示，按钮初始状态为"收起"
    setTimeout(() => {
        const contentElement = document.getElementById('ai-response-content');
        const expandBtn = document.getElementById('expand-btn');
        if (contentElement && expandBtn) {
            // 默认显示完整内容
            contentElement.classList.add('expanded');
            expandBtn.textContent = '收起内容';
            expandBtn.onclick = toggleAIResponseCollapse;
            expandBtn.style.display = 'inline-block';
        }
    }, 100);
}

// 清理AI响应格式 - 结构化渲染，避免长文本误判为不完整
function cleanAIResponse(text) {
    if (!text) return '';
    const escapeHtml = (s) => s.replace(/[&<>"']/g, (m) => ({
        '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
    }[m]));
    const lines = text.replace(/\r\n/g, '\n').split('\n').map(l => l.trim());
    const out = [];
    let currentGroup = null, currentItems = [];
    const flushGroup = () => {
        if (currentGroup) {
            out.push(`<div class="ai-project-group">${escapeHtml(currentGroup)}</div>`);
            if (currentItems.length) {
                out.push('<ol class="ai-work-list">');
                for (const item of currentItems) out.push(`<li class="ai-work-item">${escapeHtml(item)}</li>`);
                out.push('</ol>');
            }
        }
        currentGroup = null; currentItems = [];
    };
    const isEnumeratedItem = (line) => /^\d+[、.]\s*/.test(line) || /^[-•]\s+/.test(line);
    const extractItemContent = (line) => {
        const m = line.match(/^\s*(\d+)[、.]\s*(.+)$/);
        if (m) return m[2].trim();
        const b = line.match(/^\s*[-•]\s*(.+)$/);
        if (b) return b[1].trim();
        return line;
    };
    const isGroupHeader = (line) => {
        if (!line) return false;
        if (/^(第\d+批)/.test(line)) return false;
        if (/^【.*】$/.test(line)) return false;
        return !isEnumeratedItem(line);
    };
    for (const line of lines) {
        if (!line) continue;
        if (isEnumeratedItem(line)) {
            if (!currentGroup) currentGroup = '未命名项目组';
            currentItems.push(extractItemContent(line));
            continue;
        }
        if (isGroupHeader(line)) { flushGroup(); currentGroup = line; continue; }
        flushGroup();
        out.push(`<p class="ai-response-paragraph">${escapeHtml(line)}</p>`);
    }
    flushGroup();
    return out.join('');
}

// 展开AI响应内容
function toggleAIResponseExpand() {
    const contentElement = document.getElementById('ai-response-content');
    const expandBtn = document.getElementById('expand-btn');
    
    if (contentElement && expandBtn) {
        contentElement.classList.add('expanded');
        expandBtn.textContent = '收起内容';
        expandBtn.onclick = toggleAIResponseCollapse;
    }
}

// 收起AI响应内容
function toggleAIResponseCollapse() {
    const contentElement = document.getElementById('ai-response-content');
    const expandBtn = document.getElementById('expand-btn');
    
    if (contentElement && expandBtn) {
        contentElement.classList.remove('expanded');
        expandBtn.textContent = '展开全部';
        expandBtn.onclick = toggleAIResponseExpand;
        
        // 滚动到AI响应区域
        contentElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
}

// 复制AI响应内容
function copyAIResponse() {
    const contentElement = document.getElementById('ai-response-content');
    
    if (contentElement) {
        // 获取纯文本内容
        const textContent = contentElement.innerText || contentElement.textContent;
        
        // 创建临时文本区域进行复制
        const textarea = document.createElement('textarea');
        textarea.value = textContent;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        
        try {
            textarea.select();
            document.execCommand('copy');
            
            // 显示复制成功提示
            const expandBtn = document.getElementById('expand-btn');
            if (expandBtn) {
                const originalText = expandBtn.textContent;
                expandBtn.textContent = '复制成功!';
                expandBtn.classList.remove('btn-outline-secondary');
                expandBtn.classList.add('btn-success');
                
                setTimeout(() => {
                    expandBtn.textContent = originalText;
                    expandBtn.classList.remove('btn-success');
                    expandBtn.classList.add('btn-outline-secondary');
                }, 2000);
            }
        } catch (err) {
            console.error('复制失败:', err);
            alert('复制失败，请手动选择复制');
        } finally {
            document.body.removeChild(textarea);
        }
    }
}

// 清空AI问题
function clearAIQuestion() {
    const questionElement = document.getElementById('aiQuestion');
    const resultDiv = document.getElementById('aiResult');
    
    if (questionElement) questionElement.value = '';
    if (resultDiv) resultDiv.innerHTML = '';
}

// 显示错误信息
function showError(container, message) {
    container.style.display = 'block';
    container.innerHTML = `<div class="error">❌ ${message}</div>`;
}

// 显示成功信息
function showSuccess(container, message) {
    container.style.display = 'block';
    container.innerHTML = `<div class="success">✅ ${message}</div>`;
}